#ifndef _HLFS_MISC_H_
#define _HLFS_MISC_H_

#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#include <fcntl.h>
//#include "hlfs.h"
#include "address.h"
#include "storage.h"
#include "bs_local.h"

static uint64_t get_current_time(void)
{
	struct timeval t;

	if (gettimeofday(&t, NULL)) {
		g_message("Get current time error!\n");
		return -1;
	}
	return (uint64_t) t.tv_sec * 1000 + t.tv_usec / 1000;	
}

static char *build_segfile_name(uint64_t segno)
{
    	char s[64];
    	sprintf(s, "%llu", segno);
    	gchar * segfile_name = g_strconcat(s, ".", "seg", NULL);
    	return segfile_name;
}

static char *build_segfile_name_by_address(uint64_t storage_address)
{
	uint32_t segno  = get_segno(storage_address);
    	char s[64];
    	sprintf(s, "%d", segno);
    	gchar * segfile_name = g_strconcat(s,".","seg",NULL);
    	return segfile_name;
}

static char *read_block(struct back_storage *storage ,uint64_t storage_address,uint32_t block_size)
{
    int ret = 0;
    uint32_t offset = get_offset(storage_address); 
    gchar * segfile_name = build_segfile_name(get_segno(storage_address));

    g_message("%s -- segfile: %s\n", __func__, segfile_name);
    if (-1 == storage->bs_file_is_exist(storage, segfile_name)) { /* fixed */
	    segfile_name = build_segfile_name(get_segno(storage_address) - 1llu);
		if (-1 == storage->bs_file_is_exist(storage, segfile_name)) { /* fixed */
	    		segfile_name = build_segfile_name(get_segno(storage_address) + 1llu);
    		}
    }
    bs_file_t file = storage->bs_file_open(storage,segfile_name,BS_READONLY); 
    if(file==NULL){
        g_message("2 -------------> can not open segment file %s\n",segfile_name);
        ret=-1;
        goto out2;
    }

    char * block = (char*)g_malloc0(block_size);
    if (NULL == block) {
	printf("%s - Allocate Error!\n");
	block = NULL;
	goto out1;
    }
    if(block_size != storage->bs_file_pread(storage,file,block,block_size,offset)){
        g_free(block);
        block = NULL;
        goto out1;
    }

out1:
    storage->bs_file_close(storage,file);
out2:
    	g_free(segfile_name);    	
    	return block;
}

#endif 
